package org.catpay.common.xss;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;

/**
 * XSS过滤
 */
public class XssFilter implements Filter {
	private String[] ignoresParam = new String[]{};
	@Override
	public void init(FilterConfig config) throws ServletException {
		 String path = config.getInitParameter("exclusions");
		 if(StrUtil.isNotEmpty(path)) {
			 ignoresParam = path.split(",");
		 }
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
		 HttpServletRequest request = (HttpServletRequest) req;
	        HttpServletResponse response = (HttpServletResponse) res;
		  String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
		 for(String s : ignoresParam) {
			 if(s.equals(path)) {
				chain.doFilter(req, res);
				return;
			}
		 }
		  
			XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
					(HttpServletRequest) request);
			chain.doFilter(xssRequest, response);
	
	}

	@Override
	public void destroy() {
	}

}